import {Component, OnInit, Input, ChangeDetectionStrategy, ViewEncapsulation, OnChanges} from '@angular/core';
import PhotoSwipe from 'photoswipe';
import * as PhotoSwipeUI_Default from 'photoswipe/dist/photoswipe-ui-default.js';
@Component({
  selector: 'seed-photo-viewer',
  templateUrl: './photo-viewer.component.html',
  styleUrls: ['./photo-viewer.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None
})
export class PhotoViewerComponent implements OnInit, OnChanges {
  public _list = [];
  public _index: number;
  public length: number;
  public intercept: boolean = true;

  @Input()
  get list() {
    return this._list;
  }

  set list(arr) {
    this.setPhotos(arr);
  }

  @Input()
  get index() {
    return this._index;
  }

  set index(val: number) {
    this._index = val;
  }

  constructor() {
  }

  setPhotos(arr, target?) {
    const keys = Object.keys(arr);
    const o = target ? target : this._list;
    keys.map(item => {
      o.push({
        src: arr[item]['fileName'],
        w: 414,
        h: 667
      });
    });
  }

  setArray(target) {
    const tmp = [];
    const keys = Object.keys(target);
    keys.map(item => {
      tmp.push({
        src: target[item]['src'],
        w: 0,
        h: 0
      });
    });
    return tmp;
  }

  ngOnChanges() {
    if (this.list.length > 0 && this.intercept) {
      this.intercept = false;

      const v: number = Number(this.index);
      const options: any = {
        index: v,
        preventHide: true,
        allowUserZoom: false,
        captionAndToolbarShowEmptyCaptions: false,
        preventSlideshow: true,
        zIndex: '101',
        escKey: false,
        closeOnVerticalDrag: false,
        imageScaleMethod: 'zoom',
        arrowKeys: false,
        captionAndToolbarAutoHideDelay: 3333,
        history: false,
        showAnimationDuration: 0,
        hideAnimationDuration: 0,
        errorMsg: '<div class="pswp__error-msg"><a href="%url%" target="_blank">此图片</a>无法加载~</div>'
      };

      let items = Object.assign({}, this.list);
      items = this.setArray(items);
      const pswpElement: any = document.querySelectorAll('.pswp')[0];
      const gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
      gallery.listen('imageLoadComplete', function (index, item) {
        if (item.w < 1 || item.h < 1) {
          const img = new Image();
          img.onload = function () {
            item.w = img.width;
            item.h = img.height;
            gallery.invalidateCurrItems();
            gallery.updateSize(true);
          };
          img.src = item.src;
        }
      });
      gallery.init();
    }
  }


  ngOnInit() {
  }

}
